﻿using System;
using System.Collections.Generic;
using System.Linq;
using HK.Core.Extend;
using HK.Core.Utils;
using HK.Editor.Common;
using HK.Editor.GUIEx.Styles;
using UnityEditor;
using UnityEngine;

namespace HK.Editor.GUIEx.Helper
{
    public sealed class UnityDefaultIconsViewer : EditorWindow
    {
        
        private static GUIStyle _btnStyleNormal = null;
        protected static GUIStyle BtnStyleNormal 
        {
            get
            {
                if (null != _btnStyleNormal) return _btnStyleNormal;
                _btnStyleNormal = GuiExHelper.CloneStyle("EditModeSingleButton");
                _btnStyleNormal.alignment = TextAnchor.MiddleLeft;

                _btnStyleNormal.padding.left += 5;
                _btnStyleNormal.richText = true;
                _btnStyleNormal.wordWrap = true;
                _btnStyleNormal.padding.right += 5;

                return _btnStyleNormal;
            }
        }

#if UGUIEX_HELPER_ENABLE
        [MenuItem(EditorConst.MENU_TXT_UNITY_DEFAULT_GUI_ICONS_VIEW, false, EditorConst.MENU_PRIORITY_UNITY_DEFAULT_GUI_ICONS_VIEW)]
#endif
        private static void OpenGUIIcon()
        {
            icons = new List<Texture>(Resources.FindObjectsOfTypeAll<Texture>());
            var wnd = GetWindow<UnityDefaultIconsViewer>("默认Icon预览表");
            wnd.minSize = new Vector2(840, 480);
            wnd.maxSize = new Vector2(840, 480);
            
            wnd.Show();
        }

        private Vector2 scrollPosition;
        private static List<Texture> icons;
        private string _searchKey = "";
        private bool _showName = false;
        private const float No_width = 50f;
        private const float width = 200f;

        private List<string> IconNames = null;

        private void OnGUI()
        {
            if (null == icons || 0 >= icons.Count) return;
            if (null == IconNames)
            {
                IconNames = new List<string>();
                
                for (var i = 0; i < icons.Count; i++)
                {
                    var icon = icons[i];
                    if(null == icon) continue;
                    
                    var iconName = icon.name;
                    if(string.IsNullOrEmpty(iconName)) continue;
                    
                    // 工程内Icon
                    if(UtilsIo.IsAssetPath(iconName, out var oAssetPath)) continue;
                    
                    IconNames.Add(iconName);
                }
            }
            
            GUILayout.BeginHorizontal("Toolbar");
            {
                GUILayout.Label("Search:", GUILayout.Width(50));
                _searchKey = GUILayout.TextField(_searchKey, "SearchTextField");
                
                GUILayout.Label($"名字({IconNames.Count}/{icons.Count}):", GUILayout.Width(100));
                _showName = GUILayout.Toggle(_showName, "", GUILayout.Width(30));
            }
            GUILayout.EndHorizontal();
            scrollPosition = GUILayout.BeginScrollView(scrollPosition);
            {
                var widthTmp = _showName ? width: No_width; 
                var count = Mathf.FloorToInt((position.width - 10) / (widthTmp + 3f));
                var curIconNames = IconNames.Where(iO => iO.ToLower().Contains(_searchKey.ToLower())).ToList();
                for (var i = 0; i < curIconNames.Count; i += count)
                {
                    GUILayout.BeginHorizontal();
                    for (var j = 0; j < count; j++)
                    {
                        var index = i + j;
                        if (index < curIconNames.Count)
                        {
                            var iconName = curIconNames[index];
                            var content = EditorGUIUtility.IconContent(iconName);
                            if (_showName)
                            {
                                if (null != content)
                                {
                                    content.text = $"({index}){iconName}";
                                    content.tooltip = iconName;
                                }   
                            }

                            try
                            {
                                if (_showName)
                                {
                                    if (GUILayout.Button(content, BtnStyleNormal,GUILayout.Width(widthTmp), GUILayout.Height(30)))
                                    {
                                        EditorGUIUtility.systemCopyBuffer = curIconNames[index];
                                        this.Info("IconName:{0}", curIconNames[index]);
                                    }
                                }
                                else
                                {
                                    if (GUILayout.Button(content,GUILayout.Width(widthTmp), GUILayout.Height(30)))
                                    {
                                        EditorGUIUtility.systemCopyBuffer = curIconNames[index];
                                        this.Info("IconName:{0}", curIconNames[index]);
                                    }
                                }
                            }
                            catch (Exception exp)
                            {
                                this.Fatal("OnGUI():Exception:{0} - {1}\n  Icon:{2}",
                                    exp.GetType().Name, exp.Message, iconName);
                                using (new BackgroundColorScope(Color.red))
                                {
                                    if (GUILayout.Button(iconName,GUILayout.Width(widthTmp), GUILayout.Height(30)))
                                    {
                                        EditorGUIUtility.systemCopyBuffer = curIconNames[index];
                                        this.Info("IconName:{0}", curIconNames[index]);
                                    }
                                }
                            }
                    
                            var lastRect = GUILayoutUtility.GetLastRect();
                            if (Event.current.type == EventType.ContextClick  && lastRect.Contains(Event.current.mousePosition))
                            {
                                ShowDependMenus(curIconNames[index]);
                                Event.current.Use();
                            }
                        }
                    }
                    GUILayout.EndHorizontal();
                }
            }
            GUILayout.EndScrollView();
        }
        
        /// <summary>
        /// 显示依赖目标菜单
        /// </summary>
        /// <param name="iCurDepend">当前依赖</param>
        private void ShowDependMenus(string iCurDepend)
        {
            if(string.IsNullOrEmpty(iCurDepend) || iCurDepend.ToLower().EndsWith(".cs")) return;
            
            var menu = new GenericMenu();
            menu.AddItem(new GUIContent("导出Icon"), false, ExportIcon, iCurDepend);
            menu.ShowAsContext();
        }

        /// <summary>
        /// 导出Icon
        /// </summary>
        /// <param name="iProperty">Icon Property</param>
        private void ExportIcon(object iProperty)
        {
            
        }
    }
}